package com.lion.seaman.common.tools;

import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liyongyao on 2017/1/23.
 */
public class FileTools {
    static Logger log = Logger.getLogger(FileTools.class);

    public static String readFile(File file) {
        if (file == null || !file.exists()) {
            return null;
        } else {
            StringBuilder result = new StringBuilder();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line).append("\n");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result.toString();
        }
    }

    public static List<File> split(File file, Long maxSize, String prefixFormat) throws IOException {
        List<File> files = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
        BufferedOutputStream bos = null;
        long size = 0l;
        int index = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            if (bos == null || size >= maxSize) {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
                File out = new File(file.getAbsolutePath() + String.format(prefixFormat, index++));
                log.info(StringTools.format("file part {0}", out.getName()));
                files.add(out);
                bos = new BufferedOutputStream(new FileOutputStream(out));
                size = 0l;
            }
            bos.write(line.getBytes());
            bos.write('\n');
            size += line.getBytes().length;
        }
        bos.flush();
        bos.close();
        return files;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(FileTools.split(new File("d:/1.txt"), 1024 * 5l, "%05d"));
    }
}
